package edu.umn.cs5115.scheduler.search;

import edu.umn.cs5115.scheduler.SearchListener;
import edu.umn.cs5115.scheduler.SearchQuery;
import edu.umn.cs5115.scheduler.WebInterface;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import edu.umn.cs5115.scheduler.SchedulerDocument;
import edu.umn.cs5115.scheduler.entities.Course;
import edu.umn.cs5115.scheduler.framework.*;

public class SearchResults extends KeyValueCodingBase
{
    public static final String SEARCH_COMPLETED_KEY = "searchCompleted";
    
	private Course currentlySelected;
	private SchedulerDocument document;
	
	private List<Course> courses;
	private int resultsSize = 0;
        
        private SearchQuery query;
        private Hashtable<String, Object> params;
        private org.eclipse.swt.widgets.List displayList;
        
        private boolean searchCompleted = false;
	
	public SearchResults(SearchQuery query, SchedulerDocument _document)
	{
            
			this.query = query;
			params = query.getParams();
            courses = null;
            document = _document;
            
            query.addListener(new SearchListener()
            {
                public void searchCompleted(List<Course> results)
                {
                    courses = results;
                    if (displayList != null && !displayList.isDisposed())
                        populateCourseList();
                    setSearchCompleted(true);
                }
                public void searchError()
                {
                    document.displayDocumentError("An error occurred while searching.  Please check your internet connection and try again.");
                    setSearchCompleted(true);
                }
            });
            WebInterface.getWebInterface().search(query, document);
	}
	
	public SearchResults()
	{
		//empty constructor for testing...
	}
	
	public boolean isCourseConsidered(Course _course)
	{
		return document.getSchedule().getCourses().contains(_course);	
	}
	
	
	public void addToConsideringCourses(Course _course)
	{
		if(!document.getSchedule().getCourses().contains(_course))
			document.getSchedule().addCourse(_course);
	}

	public void addSelectedToConsideringCourses() 
	{
		if( currentlySelected != null && !document.getSchedule().getCourses().contains(currentlySelected) )
                {
			document.getSchedule().addCourse(currentlySelected);
			document.getUndoManager().setActionName("Add course \"" + currentlySelected.getShortName() + "\"");
                }
	}

	public void setCourseList(org.eclipse.swt.widgets.List _courses) {
            displayList = _courses;
            populateCourseList();
	}
        
    private void populateCourseList()
    {
        if (courses != null && displayList != null)
        {
            displayList.removeAll();
            try
            {
                Iterator<Course> iter = courses.iterator();
                while(iter.hasNext())
                {
                    Course temp = iter.next();
                    displayList.add(temp.getDepartment() + " " + temp.getCourseNumber() + " - " + temp.getName());
                    //formatting
                }
            }
            catch(NullPointerException e)
            {
                //do nothing!
            }
        }
        
    }
    public String getSearchParamList()
    {
        //ok for now, but later iterate through params
    	System.out.println("getSearchParamList been called yo.");
    	String prettyParams = "";
        if ( params.containsKey("searchSubjects") )
        {
        	ArrayList<String> subjects = (ArrayList<String>)params.get("searchSubjects");
        	if (subjects.size() > 1)
        		prettyParams += "Subjects: ";
        	else
        		prettyParams = "Subject: ";
        	for(String subject : subjects)
        		prettyParams+=subject.replace("*", "") + ", ";
        	prettyParams = prettyParams.substring(0, prettyParams.length() - 2) + "\n";
        }
        if ( params.containsKey("searchCatalogNumber") )
        	prettyParams += "Course Number: " + params.get("searchCatalogNumber") + "\n";
        String[] searchTerms = {"searchMon", "searchTue", "searchWed", "searchThu", "searchFri"};
        if ( params.containsKey("searchMon") || params.containsKey("searchTue") || params.containsKey("searchWed") || params.containsKey("searchThu") || params.containsKey("searchFri"))
        {
        	prettyParams += "Days: ";
        	
        	for(String term : searchTerms)
        	{
        		if( params.containsKey(term) && params.get(term) == "true" )
        			prettyParams += WebInterface.humanSearchKeys.get(term) + ", ";
        	}
        	prettyParams = prettyParams.substring(0, prettyParams.length() - 2);
        }
        System.out.println(prettyParams);
        return prettyParams;
    	//TODO : implement after wednesday if time allows
        /*for(String key: query.getParams().keySet())
        {
        	
        }*/
    }
    
	public Course getCurrentlySelected() {
		return currentlySelected;
	}

	public void setCurrentlySelected(Course currentlySelected) {
		this.currentlySelected = currentlySelected;
	}

	public void setCurrentlySelected(int _selection) {
		this.currentlySelected = courses.get(_selection);
	}

	public int getResultsSize() {
            if (courses == null)
                return 0;
            else
		return courses.size();
	}

    public boolean isSearchCompleted()
    {
        return searchCompleted;
    }

    private void setSearchCompleted(boolean searchCompleted)
    {
        if (this.searchCompleted != searchCompleted)
        {
            this.searchCompleted = searchCompleted;
            didChangeValueForKey(SEARCH_COMPLETED_KEY);
        }
    }

    void cancelSearch()
    {
        if (!searchCompleted)
            query.cancelSearch();
    }
}
